<template>
  <div>
    <el-upload
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :class="{disable: fileList.length > 0}"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-progress
      v-if="showProgress"
      :percentage="percent"
      :show-text="false"
      style="width:146px"
    />

    <!-- 预览 -->
    <el-dialog title="预览" :visible="showDialog" @close="showDialog = false">
      <el-row type="flex" justify="center">
        <img style="width:80%" :src="imgUrl" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKID96nEPJwINBizyh9gwwf7ICqDKAj13nGS',
  SecretKey: 'xe4D5i6D3dw4vVoqc7LJ0QZR3OSFkzyg'
})
export default {
  data() {
    return {
      fileList: [
        // {
        //   name: '111.jpg',
        //   url: require('@/assets/common/bigUserHeader.png')
        // }
      ],
      showDialog: false,
      imgUrl: '',
      showProgress: false,
      percent: 0
    }
  },
  methods: {
    //   预览
    onPreview(file) {
      this.showDialog = true
      this.imgUrl = file.url
    },
    // 删除
    onRemove(file, fileList) {
    //   console.log(file, fileList)
      this.fileList = [...fileList]
    },
    // 改变
    onChange(file, fileList) {
      this.fileList = [...fileList]
    },
    beforeUpload(file) {
      console.log(file)
      const size = 200 * 1024
      const whiteList = ['image/jpeg', 'image/png']
      if (whiteList.indexOf(file.type) === -1) {
        this.$message.error('图片格式必须为jpg或png')
        return false
      }
      if (file.size > size) {
        this.$message.error('图片大小限制在200kb内')
        return false
      }
    },
    // 覆盖默认的上传
    upload(data) {
      this.showProgress = true
      console.log(data)
      cos.putObject({
        Bucket: 'heima-renzi-1307117927', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(progressData)
          //   百分比
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList[0].url = `http://${data.Location}`
          this.fileList[0].status = 'success'
          setTimeout(() => {
            this.showProgress = false
          }, 500)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.disable{
    ::v-deep .el-upload--picture-card{
        display: none;
    }
}
</style>
